package util;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.logging.*;

public class LogUtils {
    private static final Logger logger = Logger.getLogger("logger");

    public static Logger getLogger() {
        logger.setLevel(Level.ALL);
        for (Handler h : logger.getHandlers()) {
            //防止出现多个日志文件
            h.close();
        }
        try {
            FileHandler fileHandler = new FileHandler("F:\\logger\\logger.txt");
            fileHandler.setFormatter(new MyLogger());
//            fileHandler.setFormatter(SimpleFormatter);
            logger.addHandler(fileHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return logger;
    }
}

/**
 * 自定义日志输出格式
 */
class MyFormat extends Formatter {
    @Override
    public String format(LogRecord record) {
        ZonedDateTime zdf = ZonedDateTime.now();
        String sDate = zdf.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return "[time：" + sDate + "]——" + "[level：" + record.getLevel().getName() + "]——" + "[location：" + record.getSourceClassName() + " " + record.getSourceMethodName() + "]——" + "[message：" + record.getMessage() + "]\n";
    }
}
